package de.appengine.facebook.api.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.appengine.facebook.api.client.FacebookGraphAPIService;
import de.appengine.facebook.api.shared.model.FacebookUser;
import de.appengine.facebook.api.shared.model.json.GetFriendsResponse;

import com.google.gson.Gson;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class FacebookServlet extends RemoteServiceServlet implements
		FacebookGraphAPIService {
	
	// TODO get token from facebook!
	private static final String accessToken = "2227470867|2.nGNvg2t8iAmUyiUxH86Z4g__.3600.1304780400.0-1630521388|lW_DRZM9i5RvZVXfHc7wtQofMhI";
	private static final String applicationID = "198252273549647";
	private static final String redirectURL = "127.0.0.1/facebook";
	
	@Override
	public List<FacebookUser> getFriends(FacebookUser user) throws Exception{
		String content = getURLContent("https://graph.facebook.com/me/friends",true);
        Gson gson = new Gson();
        return (gson.fromJson(content, GetFriendsResponse.class)).data;
	}
	
	private String getURLContent(String urlString,boolean withAccessToken) throws Exception{
		String result = "";
		String resultURL;
		if(withAccessToken){
			resultURL =urlString+"?access_token="+URLEncoder.encode(accessToken);
		} else {
			resultURL = urlString;
		}
		URL url = new URL(resultURL);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setDoOutput(true);
		connection.setRequestMethod("GET");
		int responseCode = connection.getResponseCode();
		String s = connection.getResponseMessage();
		if (responseCode == HttpURLConnection.HTTP_OK) {
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = reader.readLine()) != null) {
				result += line;
			}
			reader.close();
			return result;
		} else {
			throw new Exception();
		}
	}

}
